import store from "@/store";
import Vue from "vue";
import Component from "vue-class-component";
import storage from "@/libs/storage";

// You can declare a mixin as the same style as components.
@Component
export default class DialogMixin extends Vue {
    /**
     * 关闭弹窗
     */
    async closeHandle() {
        try {
            const result = await this.confirmHandle();
            if (result === "confirm") {
                this.dialogVisible = false;
            }
        } catch (e) {
            console.log(e);
        }
    }

    async beforeCloseHandle(done) {
        try {
            const result = await this.confirmHandle();
            if (result === "confirm") {
                done();
            }
        } catch (e) {
            console.log(e);
        }

    }

    /**
     * 关闭确认
     */
    async confirmHandle() {
        return await this.$confirm("确定退出该窗口？退出后，数据可能不保留！", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        });
    }
}

/**
 * 切换为登录状态
 */
export function modifySignStatus(token, userInfo) {
    store.dispatch("user/setToken", token);
    store.dispatch("user/setUserInfo", userInfo);
}

/**
 * 创建微信扫码iframe窗口
 */
export function createQrCode(object) {
    const c = "true";
    const d = document.createElement("iframe");
    d.src = object.url;
    setTimeout(() => {
        d.frameBorder = "0";
        d.scrolling = "no";
        d.width = "100%";
        d.height = object.height;
        d.id = "iframeId";
        const f = document.getElementById(object.id);
        f.innerHTML = "";
        f.appendChild(d);
    }, 100);
}

/**
 * 简单的节流函数
 */
export function throttle(func, wait, mustRun) {
    let timeout;
    let startTime: any = new Date();

    return () => {
        const context = this;
        const args = arguments;
        const curTime: any = new Date();

        clearTimeout(timeout);
        // 如果达到了规定的触发时间间隔，触发 handler
        if (curTime - startTime >= mustRun) {
            func.apply(context, args);
            startTime = curTime;
            // 没达到触发间隔，重新设定定时器
        } else {
            timeout = setTimeout(func, wait);
        }
    };
}

/**
 * localStorage里存入登录信息
 * @param token
 * @param userInfo
 */
export function login(token, userInfo) {
    const time = new Date();
    storage.set("time", time.getTime());
    storage.set("token", token);
    storage.set("userInfo", userInfo);
}

/**
 * 清除localStorage登录信息
 */
export function logout() {
    storage.delete("time");
    storage.delete("token");
    storage.delete("userInfo");
}
